﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MethodWorx.CMS.Services;
using MethodWorx.Core.DomainModel;
using System.Web.Security;

namespace MethodWorx.CMS.UI.Controllers
{
    public class LoginController : Controller
    {
        private UserService users;
        private IUnitOfWorkFactory uowFactory;

        public LoginController(IUnitOfWorkFactory uowFactory, UserService users)
        {
            this.users = users;
            this.uowFactory = uowFactory;
        }
        //
        // GET: /Login/
        [HttpGet]
        public ActionResult Index(bool? expired)
        {
            FormsAuthentication.SignOut();
            if ((expired ?? false) == true)
                this.ViewData["message"] =
                    "Your session has expired, please reenter your user details to log back in";

            return View();
        }

        [HttpPost]
        public ActionResult Index(string username, string password)
        {
            try
            {
                if(!this.users.AnyExists())
                {
                    this.users.CreateDefaultUsers(this.uowFactory);
                }

                var user = users.Authenticate(username, password);
                if (user != null)
                {
                    //
                    //  ok, we are great..
                    FormsAuthentication.RedirectFromLoginPage(user.Id.ToString(), false);
                }
                else
                    this.ModelState.AddModelError("username", "Username/Password is invalid");
            }
            catch(BusinessRuleException bre)
            {
                //  put the erorrs into the model state
                bre.AddToModelState(this.ModelState);
            }
            return View();
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index");
        }
    }
}
